package com.wzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzy.domain.ResponseResult;
import com.wzy.domain.entity.Article;
import com.wzy.domain.entity.Question;
import com.wzy.domain.vo.QuestionVO;
import com.wzy.exception.SystemException;
import com.wzy.mapper.ArticleMapper;
import com.wzy.mapper.QuestionMapper;
import com.wzy.service.QuestionService;
import com.wzy.service.UserCommonService;
import com.wzy.util.BeanCopyUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.wzy.constant.SystemConstants.RELEASE;
import static com.wzy.enums.AppHttpCodeEnum.PARAMETER_ERROR;

/**
 *
 */
@Service
@RequiredArgsConstructor
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question>
        implements QuestionService
{
    private final ArticleMapper articleMapper;
    private final QuestionMapper questionMapper;
    private final HttpServletRequest httpServletRequest;
    private final UserCommonService userCommonService;

    /**
     * 提交文章问题
     */
    @Override
    public ResponseResult<Void> postQuestion(QuestionVO questionVO)
    {
        Long userId = userCommonService.getRedisUserId(httpServletRequest);
        questionVO.setCreateBy(userId);
        Long articleId = questionVO.getArticleId();
        // 校验文章是否存在
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getArticleStatus, RELEASE);
        queryWrapper.eq(Article::getId, articleId);
        if (articleMapper.selectOne(queryWrapper) == null)
        {
            throw new SystemException(PARAMETER_ERROR, "文章不存在");
        }
        // 保存问题
        Question question = BeanCopyUtils.copyBean(questionVO, Question.class);
        save(question);
        return ResponseResult.okResult();
    }

    /**
     * 获取文章问题列表
     */
    @Override
    public ResponseResult<List<Question>> getQuestionList()
    {
        userCommonService.checkRole(httpServletRequest);
        // 查询
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        List<Question> questionList = questionMapper.selectList(queryWrapper);
        return ResponseResult.okResult(questionList);
    }

    /**
     * 删除文章问题
     */
    @Override
    public ResponseResult<Void> deleteQuestion(Long id)
    {
        userCommonService.checkRole(httpServletRequest);
        // 删除记录
        removeById(id);
        return ResponseResult.okResult();
    }

}




